// compressor.cpp

#include "compressor.h"
#define compressBound(x) (x + (x >> 12) + (x >> 14) + 11)

BOOL Compressor::CompressData(BYTE *src, DWORD srcLen, BYTE *dest, DWORD *destLen)
{
	// param validation
	if(IsBadReadPtr(src, srcLen))
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}
	if((*destLen > 0) && (IsBadWritePtr(dest, *destLen)))
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	// how big could we be?
	ULONG outLen = compressBound(srcLen);

	// is the dest buffer big enough?
	if(*destLen < outLen)
	{
		*destLen = outLen;
		SetLastError(ERROR_INSUFFICIENT_BUFFER);
		return FALSE;
	}

	int ret = compress2(dest, destLen, src, srcLen, COMPRESSION_LEVEL);

	if(ret = Z_BUF_ERROR)
	{
		SetLastError(ERROR_INSUFFICIENT_BUFFER);
		return FALSE;
	}
	if(ret = Z_MEM_ERROR)
	{
		SetLastError(ERROR_OUTOFMEMORY);
		return FALSE;
	}

	return ret == Z_OK;
}

BOOL Compressor::DecompressData(BYTE *src, DWORD srcLen, BYTE *dest, DWORD *destLen)
{
	// param validation
	if((IsBadReadPtr(src, srcLen)) || (IsBadWritePtr(dest, *destLen)))
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	// try decompressing
	int ret = uncompress(dest, destLen, src, srcLen);

	if(ret = Z_BUF_ERROR)
	{
		SetLastError(ERROR_INSUFFICIENT_BUFFER);
		return FALSE;
	}
	if(ret = Z_MEM_ERROR)
	{
		SetLastError(ERROR_OUTOFMEMORY);
		return FALSE;
	}

	return ret == Z_OK;
}
